package Async

import (
	"ali-hr/Database"
	"encoding/json"
	"github.com/gookit/goutil/dump"
	"github.com/hibiken/asynq"
)

/**
 * Created by Goland
 * User: wkk alisleepy@hotmail.com
 * Time: 2022/4/26 - 23:49
 * Desc: <生产者>
 */

// ExportDepartmentPayLoad 导出部门写入队列的参数信息
type exportDepartmentPayLoad struct {
	Name     string
	ParentId int
	LeaderId int
	Status   string
}

// CreateTask 生产者，创建Task任务
func CreateTask(typeName string, params map[string]interface{}, time int) bool {
	dump.P("=======参数信息 start=======")
	dump.P(params)
	// redis
	r := Database.Redis
	// 创建client
	client := asynq.NewClient(r)
	defer func() {
		_ = client.Close()
	}()

	// 创建任务
	var payload []byte
	if typeName == "export_department" {
		dump.P("发起导出部门任务")
		payload, _ = json.Marshal(exportDepartmentPayLoad{
			Name:     params["name"].(string),
			ParentId: params["parent_id"].(int),
			LeaderId: params["leader_id"].(int),
			Status:   params["status"].(string),
		})
	}
	//dump.P(len(payload))
	if len(payload) == 0 {
		dump.P("异步任务发起失败， 非法typeName = ", typeName)
		return false
	}
	// 创建任务
	t := asynq.NewTask(typeName, payload)

	// todo 优化，time秒后执行task
	// time = 0, 立即执行
	if time == 0 {
		_, err := client.Enqueue(t)
		if err != nil {
			dump.P(err)
			dump.P("异步任务发起失败， typeName:", typeName)
			return false
		}
	}

	return true
}
